package com.hys.app.service.erp.impl;

import cn.hutool.core.collection.CollUtil;
import com.hys.app.converter.erp.GoodsConverter;
import com.hys.app.converter.erp.ProductConverter;
import com.hys.app.framework.database.WebPage;
import com.hys.app.framework.exception.ServiceException;
import com.hys.app.framework.database.mybatisplus.base.BaseServiceImpl;
import com.hys.app.framework.rabbitmq.MessageSender;
import com.hys.app.framework.rabbitmq.MqMessage;
import com.hys.app.framework.util.StringUtil;
import com.hys.app.mapper.goods.GoodsMapper;
import com.hys.app.model.base.rabbitmq.AmqpExchange;
import com.hys.app.model.erp.dos.*;
import com.hys.app.model.erp.dto.GoodsDTO;
import com.hys.app.model.erp.dto.GoodsQueryParams;
import com.hys.app.model.erp.dto.ProductDTO;
import com.hys.app.model.erp.dto.message.GoodsChangeMessage;
import com.hys.app.model.erp.vo.GoodsVO;
import com.hys.app.model.erp.vo.ProductVO;
import com.hys.app.model.goods.dos.BrandDO;
import com.hys.app.model.goods.dos.GoodsGalleryDO;
import com.hys.app.model.goods.vo.GoodsParamsGroupVO;
import com.hys.app.service.erp.*;
import com.hys.app.service.goods.BrandManager;
import com.hys.app.service.goods.CategoryManager;
import com.hys.app.service.goods.GoodsGalleryManager;
import com.hys.app.service.goods.GoodsParamsManager;
import com.hys.app.util.ValidateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

import static com.hys.app.framework.util.CollectionUtils.convertList;

/**
 * 商品业务层实现
 *
 * @author 张崧
 * 2023-12-26 15:56:58
 */
@Service
public class GoodsManagerImpl extends BaseServiceImpl<GoodsMapper, GoodsDO> implements GoodsManager {

    @Autowired
    private GoodsConverter converter;

    @Autowired
    private ProductConverter productConverter;

    @Autowired
    private CategoryManager categoryManager;

    @Autowired
    private ProductManager productManager;

    @Autowired
    private BrandManager brandManager;

    @Autowired
    private GoodsGalleryManager goodsGalleryManager;

    @Autowired
    private GoodsParamsManager goodsParamsManager;

    @Autowired
    private MessageSender messageSender;

    @Autowired
    private GoodsLabelRelationManager goodsLabelRelationManager;

    @Autowired
    private GoodsLabelManager goodsLabelManager;

    @Autowired
    private ProductStockManager productStockManager;

    @Override
    public WebPage<GoodsVO> list(GoodsQueryParams queryParams) {
        WebPage<GoodsDO> webPage = baseMapper.selectPage(queryParams);

        Map<Long, String> categoryNameMap = categoryManager.mapNameByIds(convertList(webPage.getData(), GoodsDO::getCategoryId));
        Map<Long, String> brandNameMap = brandManager.mapNameByIds(convertList(webPage.getData(), GoodsDO::getBrandId));
        // 查询商品标签
        List<GoodsLabelRelationDO> goodsLabelRelationList = goodsLabelRelationManager.listByGoodsIds(convertList(webPage.getData(), GoodsDO::getId));
        List<GoodsLabelDO> goodsLabelList = goodsLabelManager.listByIds(convertList(goodsLabelRelationList, GoodsLabelRelationDO::getLabelId));

        return converter.combination(webPage, categoryNameMap, brandNameMap, goodsLabelRelationList, goodsLabelList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(GoodsDTO goodsDTO) {
        // 参数校验
        checkParams(goodsDTO);

        // 保存GoodsDO
        GoodsDO goodsDO = converter.combination(goodsDTO);
        super.save(goodsDO);
        Long goodsId = goodsDO.getId();

        // 保存product
        this.productManager.add(goodsDO, goodsDTO.getProductList());

        // 保存商品参数
        this.goodsParamsManager.addParams(goodsDTO.getParamList(), goodsId);

        // 保存相册
        this.goodsGalleryManager.add(goodsDTO.getImageList(), goodsId);

        // 发送商品消息
        GoodsChangeMessage message = new GoodsChangeMessage(GoodsChangeMessage.GoodsChangeType.Add, goodsId);
        this.messageSender.send(new MqMessage(AmqpExchange.ERP_GOODS_CHANGE, AmqpExchange.ERP_GOODS_CHANGE + "_ROUTING", message));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(GoodsDTO goodsDTO) {
        // 参数校验
        checkParams(goodsDTO);

        // 更新商品
        GoodsDO goodsDO = converter.combination(goodsDTO);
        super.updateById(goodsDO);

        // 更新product
        this.productManager.edit(goodsDO, goodsDTO.getProductList());

        // 添加商品参数
        this.goodsParamsManager.addParams(goodsDTO.getParamList(), goodsDTO.getId());

        // 添加相册
        this.goodsGalleryManager.edit(goodsDTO.getImageList(), goodsDTO.getId());

        // 发送商品消息
        GoodsChangeMessage message = new GoodsChangeMessage(GoodsChangeMessage.GoodsChangeType.Edit, goodsDTO.getId());
        this.messageSender.send(new MqMessage(AmqpExchange.ERP_GOODS_CHANGE, AmqpExchange.ERP_GOODS_CHANGE + "_ROUTING", message));
    }

    @Override
    public GoodsVO getDetail(Long id) {
        // 商品
        GoodsDO goodsDO = getById(id);

        // 产品列表
        List<ProductVO> productList = productConverter.convert(productManager.listByGoodsId(id));
        // 分类
        Map map = categoryManager.queryCatNameAndIs(goodsDO.getCategoryId());
        // 品牌
        BrandDO brandDO = brandManager.getModel(goodsDO.getBrandId());
        // 商品相册
        List<GoodsGalleryDO> galleryList = goodsGalleryManager.list(goodsDO.getId());
        // 商品参数
        List<GoodsParamsGroupVO> goodsParamsList = goodsParamsManager.queryGoodsParams(goodsDO.getCategoryId(), goodsDO.getId());

        return converter.convert(goodsDO, productList, map, brandDO, galleryList, goodsParamsList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids) {
        List<ProductStockDO> stockList = productStockManager.listByWarehouseAndProduct(null, ids);
        if(stockList.stream().mapToInt(ProductStockDO::getNum).sum() > 0){
            throw new ServiceException("商品已入库且剩余库存大于0，不能进行删除操作");
        }
        // 删除商品
        removeBatchByIds(ids);
        // 删除sku
        productManager.deleteByGoodsId(ids);
    }

    @Override
    public long countByCategoryId(Long categoryId) {
        return lambdaQuery().eq(GoodsDO::getCategoryId, categoryId).count();
    }

    private void checkParams(GoodsDTO goodsDTO) {
        if (ValidateUtil.checkRepeat(baseMapper, GoodsDO::getSn, goodsDTO.getSn(), GoodsDO::getId, goodsDTO.getId())) {
            throw new ServiceException("商品编号已存在");
        }

        List<ProductDTO> productList = goodsDTO.getProductList();
        if (!goodsDTO.getHaveSpec() && productList.size() > 1) {
            throw new ServiceException("单规格商品只能存在一个sku");
        }

        for (ProductDTO productDTO : productList) {
            if (goodsDTO.getHaveSpec()) {
                if (StringUtil.isEmpty(productDTO.getSn())) {
                    throw new ServiceException("产品编号不能为空");
                }
                if (CollUtil.isEmpty(productDTO.getSpecList())) {
                    throw new ServiceException("规格信息不能为空");
                }
            } else {
                // 如果是无规格，将规格列表置空，防止前端传参错误
                productDTO.setSpecList(new ProductDO.SpecList());
            }
        }
    }
}

